home *** CD-ROM | disk | FTP | other *** search
/ MacHack 1996 / MacHack 1996.toast / Presentations / Presentations ’92 / Graphics Acceleration Samples / Sample.c < prev    next >
C/C++ Source or Header  |  1991-09-06  |  46KB  |  1,526 lines

  1. /*
  2.  *
  3.  *     Copyright 1991 © SuperMac Technologies
  4.  *     All Rights Reserved
  5.  *     THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF SuperMac Technologies
  6.  *     The copyright notice above does not evidence any
  7.  *     actual or intended publication of such source code.
  8.  *
  9.  */
  10. /*------------------------------------------------------------------------------
  11. #
  12. #    Apple Macintosh Developer Technical Support
  13. #
  14. #    MultiFinder-Aware Simple Sample Application
  15. #
  16. #    Sample
  17. #
  18. #    Sample.c    -    C Source
  19. #
  20. #    Copyright © 1988 Apple Computer, Inc.
  21. #    All rights reserved.
  22. #
  23. #    Versions:    1.0                    08/88
  24. #                1.01                11/88
  25. #
  26. #    Components:    Sample.p            November 1, 1988
  27. #                Sample.c            November 1, 1988
  28. #                Sample.a            November 1, 1988
  29. #                Sample.inc1.a        November 1, 1988
  30. #                SampleMisc.a        November 1, 1988
  31. #                Sample.r            November 1, 1988
  32. #                Sample.h            November 1, 1988
  33. #                [A]Sample.make        November 1, 1988
  34. #                [C]Sample.make        November 1, 1988
  35. #                [P]Sample.make        November 1, 1988
  36. #
  37. #    Sample is an example application that demonstrates how to
  38. #    initialize the commonly used toolbox managers, operate 
  39. #    successfully under MultiFinder, handle desk accessories, 
  40. #    and create, grow, and zoom windows.
  41. #
  42. #    It does not by any means demonstrate all the techniques 
  43. #    you need for a large application. In particular, Sample 
  44. #    does not cover exception handling, multiple windows/documents, 
  45. #    sophisticated memory management, printing, or undo. All of 
  46. #    these are vital parts of a normal full-sized application.
  47. #
  48. #    This application is an example of the form of a Macintosh 
  49. #    application; it is NOT a template. It is NOT intended to be 
  50. #    used as a foundation for the next world-class, best-selling, 
  51. #    600K application. A stick figure drawing of the human body may 
  52. #    be a good example of the form for a painting, but that does not 
  53. #    mean it should be used as the basis for the next Mona Lisa.
  54. #
  55. #    We recommend that you review this program or TESample before 
  56. #    beginning a new application.
  57. #
  58. ------------------------------------------------------------------------------*/
  59.  
  60.  
  61. /* Segmentation strategy:
  62.  
  63.    This program consists of three segments. Main contains most of the code,
  64.    including the MPW libraries, and the main program. Initialize contains
  65.    code that is only used once, during startup, and can be unloaded after the
  66.    program starts. %A5Init is automatically created by the Linker to initialize
  67.    globals for the MPW libraries and is unloaded right away. */
  68.  
  69.  
  70. /* SetPort strategy:
  71.  
  72.    Toolbox routines do not change the current port. In spite of this, in this
  73.    program we use a strategy of calling SetPort whenever we want to draw or
  74.    make calls which depend on the current port. This makes us less vulnerable
  75.    to bugs in other software which might alter the current port (such as the
  76.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  77.    Hopefully, this also makes the routines from this program more self-contained,
  78.    since they don't depend on the current port setting. */
  79.  
  80.  
  81. #include <Limits.h>
  82. #include <Types.h>
  83. #include <Resources.h>
  84. #include <QuickDraw.h>
  85. #include <Fonts.h>
  86. #include <Events.h>
  87. #include <Windows.h>
  88. #include <Menus.h>
  89. #include <TextEdit.h>
  90. #include <Dialogs.h>
  91. #include <Desk.h>
  92. #include <ToolUtils.h>
  93. #include <Memory.h>
  94. #include <SegLoad.h>
  95. #include <Files.h>
  96. #include <OSUtils.h>
  97. #include <Traps.h>        
  98. #include <qdoffscreen.h>        
  99. #include <standardfile.h>        
  100. #include <Sample.h>        /* bring in all the #defines for Sample */
  101.  
  102. short xoff = 20;
  103. short yoff = 60;
  104.  
  105. long convolved = 0;
  106.  
  107. struct x{
  108.     GWorldPtr         gwp;
  109.     Rect            rect;
  110.     ControlHandle     hScroll;
  111.     ControlHandle     vScroll;
  112.     short            dx;
  113.     short            dy;
  114. };
  115.  
  116. typedef struct x **xhandle;
  117.  
  118. short picrefnum;
  119.  
  120. ControlHandle theControl;
  121.  
  122. short newvalue;
  123.  
  124. Ptr buffer;
  125. long bleft;
  126. Ptr bptr;
  127. #define    BSIZE    8192
  128.  
  129. /* The "g" prefix is used to emphasize that a variable is global. */
  130.  
  131. /* GMac is used to hold the result of a SysEnvirons call. This makes
  132.    it convenient for any routine to check the environment. */
  133. SysEnvRec    gMac;                /* set up by Initialize */
  134.  
  135. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  136.    trap is available. If it is false, we know that we must call GetNextEvent. */
  137. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  138.  
  139. /* GInBackground is maintained by our osEvent handling routines. Any part of
  140.    the program can check it to find out if it is currently in the background. */
  141. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  142.  
  143.  
  144. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  145.    actual prototypes for parameter type checking. */
  146.     void EventLoop( void );
  147.     void DoEvent( EventRecord *event );
  148.     void AdjustCursor( Point mouse, RgnHandle region );
  149.     void DoUpdate( WindowPtr window );
  150.     void DoActivate( WindowPtr window, Boolean becomingActive );
  151.     void DoContentClick( WindowPtr window, EventRecord *event );
  152.     void DrawWindow( WindowPtr window );
  153.     void AdjustMenus( void );
  154.     void DoMenuCommand( long menuResult );
  155.     Boolean DoCloseWindow( WindowPtr window );
  156.     void Terminate( void );
  157.     void Initialize( void );
  158.     void ForceEnvirons( void );
  159.     Boolean IsAppWindow( WindowPtr window );
  160.     Boolean IsDAWindow( WindowPtr window );
  161.     Boolean TrapAvailable( short tNumber, TrapType tType );
  162.     void AlertUser( void );
  163.  
  164.  
  165. /* Define HiWrd and LoWrd macros for efficiency. */
  166. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  167. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  168.  
  169. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  170.    dependency on the ordering of fields within a Rect */
  171. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  172. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  173.  
  174.  
  175. extern void _DataInit();
  176.  
  177. /* This routine is part of the MPW runtime library. This external
  178.    reference to it is done so that we can unload its segment, %A5Init. */
  179.  
  180.  
  181. #pragma segment Main
  182. main()
  183. {
  184.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  185.     
  186.     /* 1.01 - call to ForceEnvirons removed */
  187.     
  188.     /*    If you have stack requirements that differ from the default,
  189.         then you could use SetApplLimit to increase StackSpace at 
  190.         this point, before calling MaxApplZone. */
  191.     SetApplLimit(GetApplLimit()-(64*1024));
  192.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  193.  
  194.     Initialize();                    /* initialize the program */
  195.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  196.  
  197.     EventLoop();                    /* call the main event loop */
  198. }
  199.  
  200.  
  201. /*    Get events forever, and handle them by calling DoEvent.
  202.     Get the events by calling WaitNextEvent, if it's available, otherwise
  203.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  204.  
  205. #pragma segment Main
  206. void EventLoop()
  207. {
  208.     RgnHandle    cursorRgn;
  209.     Boolean        gotEvent;
  210.     EventRecord    event;
  211.  
  212.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  213.     do {
  214.         /* use WNE if it is available */
  215.         if ( gHasWaitNextEvent )
  216.             gotEvent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursorRgn);
  217.         else {
  218.             SystemTask();
  219.             gotEvent = GetNextEvent(everyEvent, &event);
  220.         }
  221.         if ( gotEvent ) {
  222.             /* make sure we have the right cursor before handling the event */
  223.             AdjustCursor(event.where, cursorRgn);
  224.             DoEvent(&event);
  225.         }
  226.         /* change the cursor (and region) if necessary */
  227.         AdjustCursor(event.where, cursorRgn);
  228.     } while ( true );    /* loop forever; we quit via ExitToShell */
  229. } /*EventLoop*/
  230.  
  231.  
  232. /* Calculate the new control maximum value and current value, whether it is the horizontal or
  233.     vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  234.     vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  235.     width to the width of the viewRect. The current values are set by comparing the offset between
  236.     the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  237.     calling ShowControl. */
  238.  
  239. #pragma segment Main
  240. void AdjustHV(isVert,control,window,canRedraw)
  241.     Boolean        isVert;
  242.     ControlHandle control;
  243.     WindowPtr     window;
  244.     Boolean        canRedraw;
  245. {
  246.     short        value, max;
  247.     short        oldValue, oldMax;
  248.     xhandle xh;
  249.     
  250.     xh = (xhandle)GetWRefCon(window);
  251.     if (xh == NULL)
  252.         return;
  253.     
  254.     oldValue = GetCtlValue(control);
  255.     oldMax = GetCtlMax(control);
  256.     if ( isVert ) {
  257.         max = (*xh)->rect.bottom - (window->portRect.bottom-window->portRect.top - kScrollbarAdjust);
  258.     } else
  259.         max = (*xh)->rect.right - (window->portRect.right-window->portRect.left - kScrollbarAdjust);
  260.     
  261.     if ( max < 0 ) max = 0;
  262.     SetCtlMax(control, max);
  263.     
  264.     if ( isVert )
  265.         value = window->portRect.top;
  266.     else
  267.         value = window->portRect.left;
  268.     
  269.     if ( value < 0 ) value = 0;
  270.     else if ( value >  max ) value = max;
  271.     
  272.     if ( isVert )
  273.         (*xh)->dy = value;
  274.     else
  275.         (*xh)->dx = value;
  276.  
  277.     SetCtlValue(control, value);
  278.     /* now redraw the control if it needs to be and can be */
  279.     if ( canRedraw || (max != oldMax) || (value != oldValue) )
  280.         ShowControl(control);
  281. } /*AdjustHV*/
  282.  
  283. /* Simply call the common adjust routine for the vertical and horizontal scrollbars. */
  284.  
  285. #pragma segment Main
  286. void AdjustScrollValues(window,canRedraw)
  287.     WindowPtr    window;
  288.     Boolean        canRedraw;
  289. {
  290.     xhandle xh;
  291.     
  292.     xh = (xhandle)GetWRefCon(window);
  293.     if (xh == NULL)
  294.         return;
  295.     AdjustHV(true, (*xh)->vScroll, window, canRedraw);
  296.     AdjustHV(false, (*xh)->hScroll, window, canRedraw);
  297. } /*AdjustScrollValues*/
  298.  
  299. #pragma segment Main
  300. void AdjustScrollSizes(window)
  301.     WindowPtr    window;
  302. {
  303.     xhandle xh;
  304.     
  305.     xh = (xhandle)GetWRefCon(window);
  306.     if (xh == NULL)
  307.         return;
  308.  
  309.     MoveControl((*xh)->vScroll, window->portRect.right - kScrollbarAdjust, -1);
  310.     SizeControl((*xh)->vScroll, kScrollbarWidth, (window->portRect.bottom - 
  311.                 window->portRect.top) - (kScrollbarAdjust - kScrollTweek));
  312.     MoveControl((*xh)->hScroll, -1, window->portRect.bottom - kScrollbarAdjust);
  313.     SizeControl((*xh)->hScroll, (window->portRect.right - 
  314.                 window->portRect.left) - (kScrollbarAdjust - kScrollTweek),
  315.                 kScrollbarWidth);
  316. } /*AdjustScrollSizes*/
  317.  
  318.  
  319. /* Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
  320.     and we don't want that). If the controls are to be resized as well, call the procedure to do that,
  321.     then call the procedure to adjust the maximum and current values. Finally re-enable the controls
  322.     by jamming a $FF in their contrlVis fields. */
  323.  
  324. #pragma segment Main
  325. void AdjustScrollbars(window,needsResize)
  326.     WindowPtr    window;
  327.     Boolean        needsResize;
  328. {
  329.     xhandle xh;
  330.     
  331.     xh = (xhandle)GetWRefCon(window);
  332.     if (xh == NULL)
  333.         return;
  334.     /* First, turn visibility of scrollbars off so we won’t get unwanted redrawing */
  335.     (*(*xh)->vScroll)->contrlVis = kControlInvisible;    /* turn them off */
  336.     (*(*xh)->hScroll)->contrlVis = kControlInvisible;
  337.     if ( needsResize )                                    /* move & size as needed */
  338.         AdjustScrollSizes(window);
  339.     AdjustScrollValues(window, needsResize);            /* fool with max and current value */
  340.     /* Now, restore visibility in case we never had to ShowControl during adjustment */
  341.     (*(*xh)->vScroll)->contrlVis = kControlVisible;    /* turn them on */
  342.     (*(*xh)->hScroll)->contrlVis = kControlVisible;
  343. } /* AdjustScrollbars */
  344.  
  345. /* Called when the window has been resized to fix up the controls and content. */
  346. #pragma segment Main
  347. void ResizeWindow(window)
  348.     WindowPtr    window;
  349. {
  350.     AdjustScrollbars(window, true);
  351.     InvalRect(&window->portRect);
  352. } /* ResizeWindow */
  353.  
  354.  
  355. /*    Called when a mouseDown occurs in the grow box of an active window. In
  356.     order to eliminate any 'flicker', we want to invalidate only what is
  357.     necessary. Since ResizeWindow invalidates the whole portRect, we save
  358.     the old TE viewRect, intersect it with the new TE viewRect, and
  359.     remove the result from the update region. However, we must make sure
  360.     that any old update region that might have been around gets put back. */
  361.  
  362. #pragma segment Main
  363. void DoGrowWindow(window,event)
  364.     WindowPtr    window;
  365.     EventRecord    *event;
  366. {
  367.     long        growResult;
  368.     Rect        tempRect;
  369.     xhandle xh;
  370.     
  371.     xh = (xhandle)GetWRefCon(window);
  372.     if (xh == NULL)
  373.         return;
  374.     SetPort(window);
  375.     tempRect = (*xh)->rect;
  376.     tempRect.left = 64;
  377.     tempRect.top = 64;
  378.     tempRect.right += kScrollbarWidth;
  379.     tempRect.bottom += kScrollbarWidth;
  380.     growResult = GrowWindow(window, event->where, &tempRect);
  381.     /* see if it really changed size */
  382.     if ( growResult != 0 ) {
  383.         SizeWindow(window, LoWrd(growResult), HiWrd(growResult), true);
  384.         ResizeWindow(window);
  385.     }
  386. } /* DoGrowWindow */
  387.  
  388. /* Do the right thing for an event. Determine what kind of event it is, and call
  389.  the appropriate routines. */
  390.  
  391. #pragma segment Main
  392. void DoEvent(event)
  393.     EventRecord    *event;
  394. {
  395.     short        part;
  396.     WindowPtr    window;
  397.     Boolean        hit;
  398.     char        key;
  399.     Point        p;
  400.     xhandle        xh;
  401.     Rect        r;
  402.  
  403.     switch ( event->what ) {
  404.         case mouseDown:
  405.             part = FindWindow(event->where, &window);
  406.             switch ( part ) {
  407.                 case inMenuBar:                /* process a mouse menu command (if any) */
  408.                     AdjustMenus();
  409.                     DoMenuCommand(MenuSelect(event->where));
  410.                     break;
  411.                 case inSysWindow:            /* let the system handle the mouseDown */
  412.                     SystemClick(event, window);
  413.                     break;
  414.                 case inContent:
  415.                     if ( window != FrontWindow() ) {
  416.                         SelectWindow(window);
  417.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  418.                     } else
  419.                         DoContentClick(window, event);
  420.                     break;
  421.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  422.                     if ( window != FrontWindow() )
  423.                         SelectWindow(window);
  424.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  425.                     xoff = 20;
  426.                     yoff = 40;
  427.                     break;
  428.                 case inGrow:
  429.                     DoGrowWindow(window, event);
  430.                     break;
  431.                 case inGoAway:
  432.                     if ( TrackGoAway(window, event->where) )
  433.                         DoCloseWindow(window); /* we don’t care if the user cancelled */
  434.                     break;
  435.                 case inZoomIn:
  436.                 case inZoomOut:
  437.                     SetPort(window);                /* the window must be the current port... */
  438.                     hit = TrackBox(window, event->where, part);
  439.                     if ( hit ) {
  440.                         SetPort(window);                /* the window must be the current port... */
  441.                         p.h = 0;
  442.                         p.v = 0;
  443.                         LocalToGlobal(&p);
  444.                         xh = (xhandle)GetWRefCon(window);
  445.                         r = (*xh)->rect;
  446.                         r.left += p.h;
  447.                         r.right += p.h + kScrollbarAdjust;
  448.                         r.top += p.v;
  449.                         r.bottom += p.v + kScrollbarAdjust;
  450.                         (*(WStateDataHandle)(((WindowPeek)window)->dataHandle))->stdState = r;
  451. /*                        EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  452.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  453.                         ResizeWindow(window);
  454.                     }
  455.                     break;
  456.             }
  457.             break;
  458.         case keyDown:
  459.         case autoKey:                        /* check for menukey equivalents */
  460.             key = event->message & charCodeMask;
  461.             if ( event->modifiers & cmdKey )            /* Command key down */
  462.                 if ( event->what == keyDown ) {
  463.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  464.                     DoMenuCommand(MenuKey(key));
  465.                 }
  466.             break;
  467.         case activateEvt:
  468.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  469.             break;
  470.         case updateEvt:
  471.             DoUpdate((WindowPtr) event->message);
  472.             break;
  473.         case kOSEvent:
  474.             switch (event->message >> 24) {        /* high byte of message */
  475.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  476.                     gInBackground = (event->message & kResumeMask) == 0;
  477.                     DoActivate(FrontWindow(), !gInBackground);
  478.                     break;
  479.             }
  480.             break;
  481.     }
  482. } /*DoEvent*/
  483.  
  484.  
  485. /*    Change the cursor's shape, depending on its position. This also calculates the region
  486.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  487.     that region, an event would be generated, causing this routine to be called,
  488.     allowing us to change the region to the region the mouse is currently in. If
  489.     there is more to the event than just “the mouse moved”, we get called before the
  490.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  491.     this is called again before we fall back into WNE. */
  492.  
  493. #pragma segment Main
  494. void AdjustCursor(mouse,region)
  495.     Point        mouse;
  496.     RgnHandle    region;
  497. {
  498.     WindowPtr    window;
  499.  
  500.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  501.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  502.         SetCursor(&qd.arrow);
  503.     }
  504. } /*AdjustCursor*/
  505.  
  506.  
  507. /*    This is called when an update event is received for a window.
  508.     It calls DrawWindow to draw the contents of an application window.
  509.     As an effeciency measure that does not have to be followed, it
  510.     calls the drawing routine only if the visRgn is non-empty. This
  511.     will handle situations where calculations for drawing or drawing
  512.     itself is very time-consuming. */
  513.  
  514. #pragma segment Main
  515. void DoUpdate(window)
  516.     WindowPtr    window;
  517. {
  518.     if ( IsAppWindow(window) ) {
  519.         BeginUpdate(window);                /* this sets up the visRgn */
  520.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  521.             DrawWindow(window);
  522.         EndUpdate(window);
  523.     }
  524. } /*DoUpdate*/
  525.  
  526.  
  527. /*    This is called when a window is activated or deactivated.
  528.     In Sample, the Window Manager's handling of activate and
  529.     deactivate events is sufficient. Other applications may have
  530.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  531.  
  532. #pragma segment Main
  533. void DoActivate(window, becomingActive)
  534.     WindowPtr    window;
  535.     Boolean        becomingActive;
  536. {
  537.     Rect        growRect;
  538.     xhandle        xh;
  539.     
  540.     xh = (xhandle)GetWRefCon(window);
  541.     if ( IsAppWindow(window) ) {
  542.         SetPort(window);
  543.         if ( becomingActive ) {
  544.             
  545.             /* the controls must be redrawn on activation: */
  546.             (*(*xh)->vScroll)->contrlVis = kControlVisible;
  547.             (*(*xh)->hScroll)->contrlVis = kControlVisible;
  548.             InvalRect(&(*(*xh)->vScroll)->contrlRect);
  549.             InvalRect(&(*(*xh)->hScroll)->contrlRect);
  550.             /* the growbox needs to be redrawn on activation: */
  551.             growRect = window->portRect;
  552.             /* adjust for the scrollbars */
  553.             growRect.top = growRect.bottom - kScrollbarAdjust;
  554.             growRect.left = growRect.right - kScrollbarAdjust;
  555.             InvalRect(&growRect);
  556.         }
  557.         else {        
  558.             /* the controls must be hidden on deactivation: */
  559.             HideControl((*xh)->vScroll);
  560.             HideControl((*xh)->hScroll);
  561.             /* the growbox should be changed immediately on deactivation: */
  562.             DrawGrowIcon(window);
  563.         }
  564.     }
  565. } /*DoActivate*/
  566.  
  567.  
  568. /*    Common algorithm for pinning the value of a control. It returns the actual amount
  569.     the value of the control changed. Note the pinning is done for the sake of returning
  570.     the amount the control value changed. */
  571.  
  572. #pragma segment Main
  573. void CommonAction(control,amount)
  574.     ControlHandle control;
  575.     short        *amount;
  576. {
  577.     short        value, max;
  578.     
  579.     value = GetCtlValue(control);    /* get current value */
  580.     max = GetCtlMax(control);        /* and maximum value */
  581.     *amount = value - *amount;
  582.     if ( *amount < 0 )
  583.         *amount = 0;
  584.     else if ( *amount > max )
  585.         *amount = max;
  586.     SetCtlValue(control, *amount);
  587.     *amount = value - *amount;        /* calculate the real change */
  588. } /* CommonAction */
  589.  
  590. #pragma segment Main
  591. pascal void VActionProc(control,part)
  592.     ControlHandle control;
  593.     short        part;
  594. {
  595.     short        amount;
  596.     WindowPtr    window;
  597.     Rect        r1, r2;
  598.     xhandle        xh;
  599.     
  600.     if ( part != 0 ) {                /* if it was actually in the control */
  601.         window = (*control)->contrlOwner;
  602.         switch ( part ) {
  603.             case inUpButton:
  604.             case inDownButton:        /* one line */
  605.                 amount = 10;
  606.                 break;
  607.             case inPageUp:            /* one page */
  608.             case inPageDown:
  609.                 amount = window->portRect.bottom-window->portRect.top-kScrollbarAdjust;
  610.                 break;
  611.         }
  612.         if ( (part == inDownButton) || (part == inPageDown) )
  613.             amount = -amount;        /* reverse direction for a downer */
  614.         CommonAction(control, &amount);
  615.         if (amount == 0)
  616.             return;
  617.         xh = (xhandle)GetWRefCon(window);
  618.         (*xh)->dy += amount;
  619.         r1 = window->portRect;
  620.         r1.right -= kScrollbarAdjust;
  621.         r1.bottom -= kScrollbarAdjust;
  622.         r2 = r1;
  623.         if (amount > 0) {
  624.             r1.bottom -= amount;
  625.             r2.top += amount;
  626.         } else {
  627.             r2.bottom += amount;
  628.             r1.top -= amount;
  629.         }
  630.         if (r1.top < r1.bottom) {
  631.             CopyBits((BitMap *)&qd.thePort->portBits, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  632.             if (amount > 0) {
  633.                 r2.top = r1.top;
  634.                 r2.bottom -= 1;
  635.             } else {
  636.                 r2.bottom = r1.bottom;
  637.                 r2.top += 1;
  638.             }
  639.             r1.left -= (*xh)->dx;
  640.             r1.right -= (*xh)->dx;
  641.             r1.top = r2.top - (*xh)->dy;
  642.             r1.bottom = r2.bottom - (*xh)->dy;
  643.             CopyBits((BitMap *)&(*xh)->gwp->portPixMap, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  644.         } else {
  645.             r2 = window->portRect;
  646.             r2.right -= kScrollbarAdjust;
  647.             r2.bottom -= kScrollbarAdjust;
  648.             r1 = r2;
  649.             r1.left -= (*xh)->dx;
  650.             r1.right -= (*xh)->dx;
  651.             r1.top -= (*xh)->dy;
  652.             r1.bottom -= (*xh)->dy;
  653.             CopyBits((BitMap *)&(*xh)->gwp->portPixMap, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  654.         }
  655.     }
  656. } /* VActionProc */
  657.  
  658.  
  659. pascal void HActionProc(control,part)
  660.     ControlHandle control;
  661.     short        part;
  662. {
  663.     short        amount;
  664.     WindowPtr    window;
  665.     Rect        r1, r2;
  666.     xhandle        xh;
  667.     
  668.     if ( part != 0 ) {                /* if it was actually in the control */
  669.         window = (*control)->contrlOwner;
  670.         switch ( part ) {
  671.             case inUpButton:
  672.             case inDownButton:        /* one line */
  673.                 amount = 10;
  674.                 break;
  675.             case inPageUp:            /* one page */
  676.             case inPageDown:
  677.                 amount = window->portRect.right-window->portRect.left-kScrollbarAdjust;
  678.                 break;
  679.         }
  680.         if ( (part == inDownButton) || (part == inPageDown) )
  681.             amount = -amount;        /* reverse direction for a downer */
  682.         CommonAction(control, &amount);
  683.         if (amount == 0)
  684.             return;
  685.         xh = (xhandle)GetWRefCon(window);
  686.         (*xh)->dx += amount;
  687.         r1 = window->portRect;
  688.         r1.right -= kScrollbarAdjust;
  689.         r1.bottom -= kScrollbarAdjust;
  690.         r2 = r1;
  691.         if (amount > 0) {
  692.             r1.right -= amount;
  693.             r2.left += amount;
  694.         } else {
  695.             r2.right += amount;
  696.             r1.left -= amount;
  697.         }
  698.         if (r1.left < r1.right) {
  699.             CopyBits((BitMap *)&qd.thePort->portBits, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  700.             if (amount > 0) {
  701.                 r2.left = r1.left;
  702.                 r2.right -= 1;
  703.             } else {
  704.                 r2.right = r1.right;
  705.                 r2.left += 1;
  706.             }
  707.             r1.top -= (*xh)->dy;
  708.             r1.bottom -= (*xh)->dy;
  709.             r1.left = r2.left - (*xh)->dx;
  710.             r1.right = r2.right - (*xh)->dx;
  711.             CopyBits((BitMap *)&(*xh)->gwp->portPixMap, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  712.         } else {
  713.             r2 = window->portRect;
  714.             r2.right -= kScrollbarAdjust;
  715.             r2.bottom -= kScrollbarAdjust;
  716.             r1 = r2;
  717.             r1.left -= (*xh)->dx;
  718.             r1.right -= (*xh)->dx;
  719.             r1.top -= (*xh)->dy;
  720.             r1.bottom -= (*xh)->dy;
  721.             CopyBits((BitMap *)&(*xh)->gwp->portPixMap, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  722.         }
  723.     }
  724. } /* HActionProc */
  725.  
  726.  
  727. #pragma segment Main
  728. pascal void SVActionProc()
  729. {
  730.     ControlHandle control;
  731.     short        amount, value;
  732.     WindowPtr    window;
  733.     Rect        r1, r2;
  734.     xhandle        xh;
  735.     Point        p;
  736.     
  737.     control = theControl;
  738.     window = (*control)->contrlOwner;
  739.     
  740.     GetMouse(&p);
  741.     r1 = (*control)->contrlRect;
  742.     r1.top += 16;
  743.     r1.bottom -= 16;
  744.     if (p.v < r1.top) {
  745.         p.v = r1.top;
  746.     } else
  747.     if (p.v > r1.bottom)
  748.         p.v = r1.bottom;
  749.         
  750.     xh = (xhandle)GetWRefCon(window);
  751.     
  752.     amount = (short)(((float)((*xh)->rect.bottom-(*xh)->rect.top - (window->portRect.bottom-window->portRect.top-kScrollbarAdjust))) *
  753.                     ((float)(p.v-r1.top))/((float)(r1.bottom-r1.top)));
  754.  
  755.     if ( amount < 0 )
  756.         amount = 0;
  757.     if (newvalue == amount)
  758.         return;
  759.     value = newvalue;
  760.     newvalue = amount;
  761.     amount = value - amount;    
  762.     
  763.     (*xh)->dy += amount;
  764.     r1 = window->portRect;
  765.     r1.right -= kScrollbarAdjust;
  766.     r1.bottom -= kScrollbarAdjust;
  767.     r2 = r1;
  768.     if (amount > 0) {
  769.         r1.bottom -= amount;
  770.         r2.top += amount;
  771.     } else {
  772.         r2.bottom += amount;
  773.         r1.top -= amount;
  774.     }
  775.     if (r1.top < r1.bottom) {
  776.         CopyBits((BitMap *)&qd.thePort->portBits, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  777.         if (amount > 0) {
  778.             r2.top = r1.top;
  779.         } else {
  780.             r2.bottom = r1.bottom;
  781.         }
  782.         r1.left -= (*xh)->dx;
  783.         r1.right -= (*xh)->dx;
  784.         r1.top = r2.top - (*xh)->dy;
  785.         r1.bottom = r2.bottom - (*xh)->dy;
  786.         CopyBits((BitMap *)&(*xh)->gwp->portPixMap, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  787.     } else {
  788.         r2 = window->portRect;
  789.         r2.right -= kScrollbarAdjust;
  790.         r2.bottom -= kScrollbarAdjust;
  791.         r1 = r2;
  792.         r1.left -= (*xh)->dx;
  793.         r1.right -= (*xh)->dx;
  794.         r1.top -= (*xh)->dy;
  795.         r1.bottom -= (*xh)->dy;
  796.         CopyBits((BitMap *)&(*xh)->gwp->portPixMap, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  797.     }
  798. } /* HActionProc */
  799.  
  800.  
  801. #pragma segment Main
  802. pascal void SHActionProc()
  803. {
  804.     ControlHandle control;
  805.     short        amount, value;
  806.     WindowPtr    window;
  807.     Rect        r1, r2;
  808.     xhandle        xh;
  809.     Point        p;
  810.     
  811.     control = theControl;
  812.     window = (*control)->contrlOwner;
  813.     
  814.     GetMouse(&p);
  815.     r1 = (*control)->contrlRect;
  816.     r1.left += 16;
  817.     r1.right -= 16;
  818.     if (p.h < r1.left) {
  819.         p.h = r1.left;
  820.     } else
  821.     if (p.h > r1.right)
  822.         p.h = r1.right;
  823.         
  824.     xh = (xhandle)GetWRefCon(window);
  825.     
  826.     amount = (short)(((float)((*xh)->rect.right-(*xh)->rect.left - (window->portRect.right-window->portRect.left-kScrollbarAdjust))) *
  827.                     ((float)(p.h-r1.left))/((float)(r1.right-r1.left)));
  828.  
  829.     if ( amount < 0 )
  830.         amount = 0;
  831.     if (newvalue == amount)
  832.         return;
  833.     value = newvalue;
  834.     newvalue = amount;
  835.     amount = value - amount;    
  836.     
  837.     (*xh)->dx += amount;
  838.     r1 = window->portRect;
  839.     r1.right -= kScrollbarAdjust;
  840.     r1.bottom -= kScrollbarAdjust;
  841.     r2 = r1;
  842.     if (amount > 0) {
  843.         r1.right -= amount;
  844.         r2.left += amount;
  845.     } else {
  846.         r2.right += amount;
  847.         r1.left -= amount;
  848.     }
  849.     if (r1.left < r1.right) {
  850.         CopyBits((BitMap *)&qd.thePort->portBits, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  851.         if (amount > 0) {
  852.             r2.left = r1.left;
  853.             r2.right -= 1;
  854.         } else {
  855.             r2.right = r1.right;
  856.             r2.left += 1;
  857.         }
  858.         r1.top -= (*xh)->dy;
  859.         r1.bottom -= (*xh)->dy;
  860.         r1.left = r2.left - (*xh)->dx;
  861.         r1.right = r2.right - (*xh)->dx;
  862.         CopyBits((BitMap *)&(*xh)->gwp->portPixMap, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  863.     } else {
  864.         r2 = window->portRect;
  865.         r2.right -= kScrollbarAdjust;
  866.         r2.bottom -= kScrollbarAdjust;
  867.         r1 = r2;
  868.         r1.left -= (*xh)->dx;
  869.         r1.right -= (*xh)->dx;
  870.         r1.top -= (*xh)->dy;
  871.         r1.bottom -= (*xh)->dy;
  872.         CopyBits((BitMap *)&(*xh)->gwp->portPixMap, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  873.     }
  874.     
  875. } /* HActionProc */
  876.  
  877.  
  878. /*    This is called when a mouse-down event occurs in the content of a window.
  879.     Other applications might want to call FindControl, TEClick, etc., to
  880.     further process the click. */
  881.  
  882. #pragma segment Main
  883. void DoContentClick(window,event)
  884.     WindowPtr    window;
  885.     EventRecord    *event;
  886. {
  887.     Point        mouse;
  888.     ControlHandle control;
  889.     short        part, value;
  890.     xhandle        xh;
  891.  
  892.     if ( IsAppWindow(window) ) {
  893.         xh = (xhandle)GetWRefCon(window);
  894.         SetPort(window);
  895.         mouse = event->where;                            /* get the click position */
  896.         GlobalToLocal(&mouse);
  897.         part = FindControl(mouse, window, &control);
  898.         switch ( part ) {
  899.             case 0:                            /* do nothing for viewRect case */
  900.                 break;
  901.             case inThumb:
  902.                 theControl = control;
  903.                 newvalue = GetCtlValue(control);
  904.                 if ( control == (*xh)->vScroll ) {
  905.                     value = TrackControl(control, mouse, (ProcPtr) SVActionProc);
  906.                 } else {
  907.                     value = TrackControl(control, mouse, (ProcPtr) SHActionProc);
  908.                 }
  909.                 SetCtlValue(control, newvalue);
  910.                 break;
  911.             default:                        /* they clicked in an arrow, so track & scroll */
  912.                 if ( control == (*xh)->vScroll ) {
  913.                     value = TrackControl(control, mouse, (ProcPtr) VActionProc);
  914.                 } else {
  915.                     value = TrackControl(control, mouse, (ProcPtr) HActionProc);
  916.                 }
  917.                 break;
  918.         }
  919.     }
  920. } /*DoContentClick*/
  921.  
  922.  
  923. /* Draw the contents of the application window. We do some drawing in color, using
  924.    Classic QuickDraw's color capabilities. This will be black and white on old
  925.    machines, but color on color machines. At this point, the window’s visRgn
  926.    is set to allow drawing only where it needs to be done. */
  927.  
  928. #pragma segment Main
  929. void DrawWindow(window)
  930.     WindowPtr    window;
  931. {
  932.     xhandle xhp;
  933.     Rect r1, r2;
  934.     GWorldPtr gwp;
  935.     PixMapHandle pm;
  936.     
  937.     SetPort(window);
  938.  
  939.     DrawControls(window);
  940.     DrawGrowIcon(window);
  941.  
  942.     xhp = (xhandle)GetWRefCon(window);
  943.     
  944.     if (xhp == NULL) {
  945.         EraseRect(&window->portRect);
  946.         return;
  947.     }
  948.     
  949.     gwp = (*xhp)->gwp;
  950.     if (gwp == NULL) {
  951. fail:    EraseRect(&window->portRect);
  952.         return;
  953.     }
  954.     r2 = window->portRect;
  955.     r2.right -= kScrollbarAdjust;
  956.     r2.bottom -= kScrollbarAdjust;
  957.     r1 = r2;
  958.     r1.left -= (*xhp)->dx;
  959.     r1.right -= (*xhp)->dx;
  960.     r1.top -= (*xhp)->dy;
  961.     r1.bottom -= (*xhp)->dy;
  962.     pm = GetGWorldPixMap(gwp);
  963.     if (!LockPixels(pm))
  964.         goto fail;
  965.     CopyBits((BitMap *)&gwp->portPixMap, &qd.thePort->portBits, &r1, &r2, srcCopy, NULL);
  966.     UnlockPixels(pm);
  967. } /*DrawWindow*/
  968.  
  969.  
  970. /*    Enable and disable menus based on the current state.
  971.     The user can only select enabled menu items. We set up all the menu items
  972.     before calling MenuSelect or MenuKey, since these are the only times that
  973.     a menu item can be selected. Note that MenuSelect is also the only time
  974.     the user will see menu items. This approach to deciding what enable/
  975.     disable state a menu item has the advantage of concentrating all
  976.     the decision-making in one routine, as opposed to being spread throughout
  977.     the application. Other application designs may take a different approach
  978.     that is just as valid. */
  979.  
  980. #pragma segment Main
  981. void AdjustMenus()
  982. {
  983.     WindowPtr    window;
  984.     MenuHandle    menu;
  985.  
  986.     window = FrontWindow();
  987.  
  988.     menu = GetMHandle(mFile);
  989.     EnableItem(menu, iOpen);
  990.     if ( window != NULL )        /* we can allow desk accessories to be closed from the menu */
  991.         EnableItem(menu, iClose);
  992.     else
  993.         DisableItem(menu, iClose);    /* but not our traffic light window */
  994.  
  995.     menu = GetMHandle(mEdit);
  996.     if ( window != NULL  && IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  997.         EnableItem(menu, iUndo);
  998.         EnableItem(menu, iCut);
  999.         EnableItem(menu, iCopy);
  1000.         EnableItem(menu, iClear);
  1001.         EnableItem(menu, iPaste);
  1002.     } else {                        /* …but we don’t use it */
  1003.         DisableItem(menu, iUndo);
  1004.         DisableItem(menu, iCut);
  1005.         DisableItem(menu, iCopy);
  1006.         DisableItem(menu, iClear);
  1007.         DisableItem(menu, iPaste);
  1008.     }
  1009.     menu = GetMHandle(mOptions);
  1010.     EnableItem(menu, iConvolve);
  1011.  
  1012. } /*AdjustMenus*/
  1013.  
  1014.  
  1015. /*    This is called when an item is chosen from the menu bar (after calling
  1016.     MenuSelect or MenuKey). It performs the right operation for each command.
  1017.     It is good to have both the result of MenuSelect and MenuKey go to
  1018.     one routine like this to keep everything organized. */
  1019.  
  1020. #pragma segment Main
  1021. void DoMenuCommand(menuResult)
  1022.     long        menuResult;
  1023. {
  1024.     short        menuID;                /* the resource ID of the selected menu */
  1025.     short        menuItem;            /* the item number of the selected menu */
  1026.     short        itemHit;
  1027.     Str255        daName;
  1028.     short        daRefNum;
  1029.     Boolean        handledByDA;
  1030.     SFReply                reply;
  1031.     Point                p;
  1032.     SFTypeList            tp;
  1033.     PicHandle             ph;
  1034.     long                x;
  1035.     short                err;
  1036.  
  1037.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  1038.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  1039.     switch ( menuID ) {
  1040.         case mApple:
  1041.             switch ( menuItem ) {
  1042.                 case iAbout:        /* bring up alert for About */
  1043.                     itemHit = Alert(rAboutAlert, nil);
  1044.                     break;
  1045.                 default:            /* all non-About items in this menu are DAs */
  1046.                     /* type Str255 is an array in MPW 3 */
  1047.                     GetItem(GetMHandle(mApple), menuItem, daName);
  1048.                     daRefNum = OpenDeskAcc(daName);
  1049.                     break;
  1050.             }
  1051.             break;
  1052.         case mFile:
  1053.             switch ( menuItem ) {
  1054.                 case iOpen:
  1055.                     p.v = 40;
  1056.                     p.h = 40;
  1057.                     tp[0] = 'PICT';
  1058.                     SFGetFile(p, "\pPICT file:", NULL, 1, &tp, NULL, &reply);
  1059.                     if (!reply.good)
  1060.                         break;
  1061.                     err = FSOpen(&reply.fName, reply.vRefNum, &picrefnum);
  1062.                     if (err != noErr)
  1063.                         break;
  1064.                     ph = (PicHandle)NewHandle(sizeof(**ph));
  1065.                     bptr = buffer = NewPtr(BSIZE);
  1066.                     bleft = 0;
  1067.                     err = SetFPos(picrefnum, fsFromStart, 512);
  1068.                     HLock((Handle)ph);
  1069.                     x = sizeof(**ph);
  1070.                     err = FSRead(picrefnum, &x, (Ptr)*ph);
  1071.                     MakeNewWindow(ph, &reply.fName);
  1072.                     DisposeHandle((Handle)ph);
  1073.                     if (buffer)
  1074.                         DisposePtr(buffer);
  1075.                     err = FSClose(picrefnum);
  1076.                     break;
  1077.                 case iClose:
  1078.                     DoCloseWindow(FrontWindow());
  1079.                     break;
  1080.                 case iQuit:
  1081.                     Terminate();
  1082.                     break;
  1083.             }
  1084.             break;
  1085.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  1086.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  1087.             break;
  1088.         case mOptions:
  1089.             switch ( menuItem ) {
  1090.                 case iConvolve:
  1091.                     convolved = 1-convolved;
  1092.                     CheckItem(GetMHandle(mOptions), iConvolve, convolved);
  1093.                     break;
  1094.             }
  1095.             break;
  1096.     }
  1097.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  1098. } /*DoMenuCommand*/
  1099.  
  1100.  
  1101. /* Close a window. This handles desk accessory and application windows. */
  1102.  
  1103. /*    1.01 - At this point, if there was a document associated with a
  1104.     window, you could do any document saving processing if it is 'dirty'.
  1105.     DoCloseWindow would return true if the window actually closed, i.e.,
  1106.     the user didn’t cancel from a save dialog. This result is handy when
  1107.     the user quits an application, but then cancels the save of a document
  1108.     associated with a window. */
  1109.  
  1110. #pragma segment Main
  1111. Boolean DoCloseWindow(window)
  1112.     WindowPtr    window;
  1113. {
  1114.     xhandle xh;
  1115.     
  1116.     if ( IsDAWindow(window) )
  1117.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  1118.     else if ( IsAppWindow(window) ) {
  1119.         xh = (xhandle)GetWRefCon(window);
  1120.         if (xh) {
  1121.             if ((*xh)->gwp)
  1122.                 DisposeGWorld((*xh)->gwp);
  1123.             DisposeHandle((Handle)xh);
  1124.         }
  1125.         CloseWindow(window);
  1126.     }
  1127.     return true;
  1128. } /*DoCloseWindow*/
  1129.  
  1130.  
  1131. /**************************************************************************************
  1132. *** 1.01 DoCloseBehind(window) was removed ***
  1133.  
  1134.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  1135.     and not having to worry about updating the windows, but it suffered
  1136.     from a fatal flaw. If a desk accessory owned two windows, it would
  1137.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  1138.     got around to calling DoCloseWindow for that other window that was already
  1139.     closed, things would go very poorly. Another option would be to have a
  1140.     procedure, GetRearWindow, that would go through the window list and return
  1141.     the last window. Instead, we decided to present the standard approach
  1142.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  1143.     has a potential benefit in that the window whose document needs to be saved
  1144.     may be visible since it is the front window, therefore decreasing the
  1145.     chance of user confusion. For aesthetic reasons, the windows in the
  1146.     application should be checked for updates periodically and have the
  1147.     updates serviced.
  1148. **************************************************************************************/
  1149.  
  1150.  
  1151. /* Clean up the application and exit. We close all of the windows so that
  1152.  they can update their documents, if any. */
  1153.  
  1154. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  1155.     shell, but will return instead. */
  1156.  
  1157. #pragma segment Main
  1158. void Terminate()
  1159. {
  1160.     WindowPtr    aWindow;
  1161.     Boolean        closed;
  1162.     
  1163.     closed = true;
  1164.     do {
  1165.         aWindow = FrontWindow();                /* get the current front window */
  1166.         if (aWindow != nil)
  1167.             closed = DoCloseWindow(aWindow);    /* close this window */    
  1168.     }
  1169.     while (closed && (aWindow != nil));
  1170.     if (closed)
  1171.         ExitToShell();                            /* exit if no cancellation */
  1172. } /*Terminate*/
  1173.  
  1174.  
  1175. /*    Set up the whole world, including global variables, Toolbox managers,
  1176.     and menus. We also create our one application window at this time.
  1177.     Since window storage is non-relocateable, how and when to allocate space
  1178.     for windows is very important so that heap fragmentation does not occur.
  1179.     Because Sample has only one window and it is only disposed when the application
  1180.     quits, we will allocate its space here, before anything that might be a locked
  1181.     relocatable object gets into the heap. This way, we can force the storage to be
  1182.     in the lowest memory available in the heap. Window storage can differ widely
  1183.     amongst applications depending on how many windows are created and disposed. */
  1184.  
  1185. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  1186.     this module. If an error is detected, instead of merely doing an ExitToShell,
  1187.     which leaves the user without much to go on, we call AlertUser, which puts
  1188.     up a simple alert that just says an error occurred and then calls ExitToShell.
  1189.     Since there is no other cleanup needed at this point if an error is detected,
  1190.     this form of error- handling is acceptable. If more sophisticated error recovery
  1191.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  1192.  
  1193. #pragma segment Initialize
  1194. void Initialize()
  1195. {
  1196.     Handle        menuBar;
  1197.     long        total, contig;
  1198.     EventRecord event;
  1199.     short        count;
  1200.  
  1201.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  1202.     gInBackground = false;
  1203.  
  1204.     InitGraf((Ptr) &qd.thePort);
  1205.     InitFonts();
  1206.     InitWindows();
  1207.     InitMenus();
  1208.     TEInit();
  1209.     InitDialogs(nil);
  1210.     InitCursor();
  1211.     
  1212.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  1213.          if you are using it. */
  1214.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  1215.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  1216.         of checking for port availability themselves. */
  1217.     
  1218.     /*    Now this next bit of code may make you toss your cookies, but it is
  1219.         necessary to allow the default button of our alert be outlined. */
  1220.      
  1221.     for (count = 1; count <= 3; count++)
  1222.         GetNextEvent(everyEvent, &event);
  1223.     
  1224.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  1225.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  1226.         call to SysEnvirons by calling it after initializing AppleTalk. */
  1227.      
  1228.     SysEnvirons(kSysEnvironsVersion, &gMac);
  1229.     
  1230.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  1231.     
  1232.     if (gMac.machineType < 0) AlertUser();
  1233.     
  1234.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  1235.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  1236.         MultiFinder we needed. This did not work well because it assumed too much about
  1237.         the relationship between what we asked MultiFinder for and what we would actually
  1238.         get back, as well as how to measure it. Instead, we will use an alternate
  1239.         method comprised of two steps. */
  1240.      
  1241.     /*    It is better to first check the size of the application heap against a value
  1242.         that you have determined is the smallest heap the application can reasonably
  1243.         work in. This number should be derived by examining the size of the heap that
  1244.         is actually provided by MultiFinder when the minimum size requested is used.
  1245.         The derivation of the minimum size requested from MultiFinder is described
  1246.         in Sample.h. The check should be made because the preferred size can end up
  1247.         being set smaller than the minimum size by the user. This extra check acts to
  1248.         insure that your application is starting from a solid memory foundation. */
  1249.      
  1250.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) AlertUser();
  1251.     
  1252.     /*    Next, make sure that enough memory is free for your application to run. It
  1253.         is possible for a situation to arise where the heap may have been of required
  1254.         size, but a large scrap was loaded which left too little memory. To check for
  1255.         this, call PurgeSpace and compare the result with a value that you have determined
  1256.         is the minimum amount of free memory your application needs at initialization.
  1257.         This number can be derived several different ways. One way that is fairly
  1258.         straightforward is to run the application in the minimum size configuration
  1259.         as described previously. Call PurgeSpace at initialization and examine the value
  1260.         returned. However, you should make sure that this result is not being modified
  1261.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  1262.         PurgeSpace. Make sure to remove that call before shipping, though. */
  1263.     
  1264.     /* ZeroScrap(); */
  1265.  
  1266.     PurgeSpace(&total, &contig);
  1267.     if (total < kMinSpace) AlertUser();
  1268.  
  1269.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  1270.         to check memory is that we can now give the user an alert to tell him/her what
  1271.         happened. Although it is possible that the memory situation could be worsened by
  1272.         displaying an alert, MultiFinder would gracefully exit the application with
  1273.         an informative alert if memory became critical. Here we are acting more
  1274.         in a preventative manner to avoid future disaster from low-memory problems. */
  1275.  
  1276.     /*     we will allocate our own window storage instead of letting the Window
  1277.         Manager do it because GetNewWindow may load in temp. resources before
  1278.         making the NewPtr call, and this can lead to heap fragmentation. */
  1279.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  1280.     if ( menuBar == nil ) AlertUser();
  1281.     SetMenuBar(menuBar);                    /* install menus */
  1282.     DisposHandle(menuBar);
  1283.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  1284.     DrawMenuBar();
  1285.     
  1286. } /*Initialize*/
  1287.  
  1288. #pragma segment Main
  1289. dprintf(char *s, long a, long b)
  1290. {
  1291.     char xx[256];
  1292.     
  1293.     sprintf(&xx[1], s, a, b);
  1294.     xx[0] = strlen(&xx[1]);
  1295.     DebugStr(xx);
  1296. }
  1297.  
  1298. pascal 
  1299. GetPICTData(Ptr data, short count)
  1300. {
  1301.     register long c1, c2;
  1302.     long c;
  1303.     register  Ptr x1, x2;
  1304.     
  1305.     if (buffer == NULL) {
  1306.         c = count;
  1307.         (void)FSRead(picrefnum, &c, data);
  1308.         return;
  1309.     }
  1310.     x2 = data;
  1311.     c1 = count;
  1312.     for (;;) {
  1313.         if (bleft >= c1) {
  1314.             x1 = bptr;
  1315.             bleft -= c1;
  1316.             while (c1--)
  1317.                 *x2++ = *x1++;
  1318.             bptr = x1;
  1319.             return;
  1320.         }
  1321.         if (c2 = bleft) {
  1322.             c1 -= c2;
  1323.             x1 = bptr;
  1324.             while (c2--)
  1325.                 *x2++ = *x1++;
  1326.         }
  1327.         bptr = buffer;
  1328.         bleft = BSIZE;
  1329.         (void)FSRead(picrefnum, &bleft, bptr);
  1330.     }    
  1331. }
  1332.     
  1333. #pragma segment Main
  1334. MakeNewWindow(PicHandle ph, char *name)
  1335. {
  1336.     WindowPtr window, window2;
  1337.     xhandle xh;
  1338.     Rect r, rg;
  1339.     GWorldPtr gwp;
  1340.     CQDProcs qdp;
  1341.     CGrafPtr oldgrp;
  1342.     GDHandle oldgd;
  1343.     PixMapHandle pm;
  1344.     char cc[70];
  1345.     long l;
  1346.     register long i, j, rb;
  1347.     register unsigned char *p, *base;
  1348.     char c;
  1349.     
  1350.     r = (*ph)->picFrame;
  1351.     r.right = r.right-r.left;
  1352.     r.bottom = r.bottom-r.top;
  1353.     r.left = 0;
  1354.     r.top = 0;
  1355.     rg.left = xoff;
  1356.     rg.right = xoff+r.right;
  1357.     rg.top = yoff;
  1358.     rg.bottom = yoff+r.bottom;
  1359.     
  1360.     GetGWorld(&oldgrp, &oldgd);
  1361.     if (NewGWorld(&gwp, 0, &rg, NULL, NULL, 0) != noErr)
  1362.         return(0);
  1363.         
  1364.     SetGWorld(gwp, NULL);
  1365.     
  1366.     SetStdCProcs(&qdp);
  1367.     gwp->grafProcs = &qdp;
  1368.     qdp.getPicProc = (Ptr)GetPICTData;
  1369.  
  1370.     pm = GetGWorldPixMap(gwp);
  1371.     
  1372.     (void)LockPixels(pm);
  1373.     
  1374.     DrawPicture(ph, &r);
  1375.  
  1376.     UnlockPixels(pm);
  1377.  
  1378.     l = (long)GetPixBaseAddr(pm);
  1379.  
  1380.     gwp->grafProcs = NULL;
  1381.     SetGWorld(oldgrp, oldgd);
  1382.     xh = (xhandle)NewHandle(sizeof(**xh));
  1383.     if (xh == NULL) {
  1384.         DisposeGWorld(gwp);
  1385.         return(0);
  1386.     }
  1387.     window = (WindowPtr) NewPtr(sizeof(WindowRecord));
  1388.     if (window == NULL) {
  1389.         DisposeGWorld(gwp);
  1390.         DisposeHandle((Handle)xh);
  1391.         return(0);
  1392.     }
  1393.     window2 = GetNewWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  1394.     if (window2 == NULL) {
  1395.         DisposeGWorld(gwp);
  1396.         DisposePtr((Ptr)window);
  1397.         DisposeHandle((Handle)xh);
  1398.         return(0);
  1399.     }
  1400.     SetWRefCon(window2, (long)xh);
  1401.     (*xh)->rect = r;
  1402.     (*xh)->gwp = gwp;
  1403.     MoveWindow(window2, rg.left, rg.top, 0);
  1404.     SizeWindow(window2, rg.right-rg.left+kScrollbarAdjust, rg.bottom-rg.top+kScrollbarAdjust,0);
  1405.     name[name[0]+1] = 0;
  1406.     strcpy(&cc[1], &name[1]);
  1407.     if (l&0x80000000) {
  1408.         strcat(&cc[1], " (onboard)");
  1409.     } else {
  1410.         strcat(&cc[1], " (main memory)");
  1411.     }
  1412.     cc[0] = strlen(&cc[1]);
  1413.     SetWTitle(window2, cc);
  1414.     xoff += 20;
  1415.     yoff += 20;
  1416.     (*xh)->vScroll = GetNewControl(rVScroll, window2);
  1417.     (*xh)->hScroll = GetNewControl(rHScroll, window2);
  1418.     (*xh)->dx = 0;
  1419.     (*xh)->dy = 0;
  1420.     AdjustScrollbars(window2,1);
  1421.     
  1422.     if (convolved) {
  1423.         base = (unsigned char *)GetPixBaseAddr(pm);
  1424.         c = 1;
  1425.         SwapMMUMode(&c);
  1426.         rb =   (*pm)->rowBytes&0x3ffe;
  1427.         p = base;
  1428.         for (i = (*pm)->bounds.left; i < (*pm)->bounds.right; i++) {
  1429.             p[1] = (((long)p[1]<<1)+0x80+p[rb+1])>>2;
  1430.             p[2] = (((long)p[2]<<1)+0x80+p[rb+2])>>2;
  1431.             p[3] = (((long)p[3]<<1)+0x80+p[rb+3])>>2;
  1432.             p += 4;
  1433.         }
  1434.         base = base + rb;
  1435.         for (j = (*pm)->bounds.top+1; j < ((*pm)->bounds.bottom-1); j++) {
  1436.             p = base;
  1437.             for (i = (*pm)->bounds.left; i < (*pm)->bounds.right; i++) {
  1438.                 p[1] = (((long)p[1]<<1)+p[-rb+1]+p[rb+1])>>2;
  1439.                 p[2] = (((long)p[2]<<1)+p[-rb+2]+p[rb+2])>>2;
  1440.                 p[3] = (((long)p[3]<<1)+p[-rb+3]+p[rb+3])>>2;
  1441.                 p += 4;
  1442.             }
  1443.             base = base + rb;
  1444.         }
  1445.         p = base;
  1446.         for (i = (*pm)->bounds.left; i < (*pm)->bounds.right; i++) {
  1447.             p[1] = (((long)p[1]<<1)+0x80+p[-rb+1])>>2;
  1448.             p[2] = (((long)p[2]<<1)+0x80+p[-rb+2])>>2;
  1449.             p[3] = (((long)p[3]<<1)+0x80+p[-rb+3])>>2;
  1450.             p += 4;
  1451.         }
  1452.         SwapMMUMode(&c);
  1453.     }
  1454.     
  1455.     ShowWindow(window2);
  1456.     return(1);
  1457. }
  1458.  
  1459. /*    Check to see if a window belongs to the application. If the window pointer
  1460.     passed was NIL, then it could not be an application window. WindowKinds
  1461.     that are negative belong to the system and windowKinds less than userKind
  1462.     are reserved by Apple except for windowKinds equal to dialogKind, which
  1463.     mean it is a dialog. */
  1464.  
  1465. #pragma segment Main
  1466. Boolean IsAppWindow(window)
  1467.     WindowPtr    window;
  1468. {
  1469.     short        windowKind;
  1470.  
  1471.     if ( window == nil )
  1472.         return false;
  1473.     else {    /* application windows have windowKinds >= userKind (8) or dialogKind (2) */
  1474.         windowKind = ((WindowPeek) window)->windowKind;
  1475.         return (windowKind >= userKind) || (windowKind == dialogKind);
  1476.     }
  1477. } /*IsAppWindow*/
  1478.  
  1479.  
  1480. /* Check to see if a window belongs to a desk accessory. */
  1481.  
  1482. #pragma segment Main
  1483. Boolean IsDAWindow(window)
  1484.     WindowPtr    window;
  1485. {
  1486.     if ( window == nil )
  1487.         return false;
  1488.     else    /* DA windows have negative windowKinds */
  1489.         return ((WindowPeek) window)->windowKind < 0;
  1490. } /*IsDAWindow*/
  1491.  
  1492.  
  1493. /*    Check to see if a given trap is implemented. This is only used by the
  1494.     Initialize routine in this program, so we put it in the Initialize segment.
  1495.     The recommended approach to see if a trap is implemented is to see if
  1496.     the address of the trap routine is the same as the address of the
  1497.     Unimplemented trap. */
  1498.  
  1499. #pragma segment Initialize
  1500. Boolean TrapAvailable(tNumber,tType)
  1501.     short        tNumber;
  1502.     TrapType    tType;
  1503. {
  1504.     /* Check and see if the trap exists. On 64K ROM machines, tType will be ignored. */
  1505.  
  1506.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  1507. } /*TrapAvailable*/
  1508.  
  1509.  
  1510. /*    Display an alert that tells the user an error occurred, then exit the program.
  1511.     This routine is used as an ultimate bail-out for serious errors that prohibit
  1512.     the continuation of the application. Errors that do not require the termination
  1513.     of the application should be handled in a different manner. Error checking and
  1514.     reporting has a place even in the simplest application. The error number is used
  1515.     to index an 'STR#' resource so that a relevant message can be displayed. */
  1516.  
  1517. #pragma segment Main
  1518. void AlertUser()
  1519. {
  1520.     short        itemHit;
  1521.  
  1522.     SetCursor(&qd.arrow);
  1523.     itemHit = Alert(rUserAlert, nil);
  1524.     ExitToShell();
  1525. } /* AlertUser */
  1526.